package com.hnluchuan.bmjlearning.security;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.RememberMeServices;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import com.hnluchuan.bmjlearning.model.User;
import com.hnluchuan.bmjlearning.web.listener.MySessionListener;

@Component
public class MyAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

	//@Autowired
	//private RememberMeServices rememberMeServices;
	
	@Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
            Authentication au) throws IOException, ServletException {
		if (au != null && au.getPrincipal() != null && au.getPrincipal() instanceof User) {
		    User user = (User) au.getPrincipal();
		    request.getSession().setAttribute("currentUser", user);
		    request.getSession().setAttribute("logined", true);
		    
		    /*for (HttpSession session : MySessionListener.sessionMap.values()) {
				if (request.getSession().getId().equals(session.getId())) {
					continue;
				}
				User old = (User) session.getAttribute("currentUser");
				if (old != null && old.getId().equals(user.getId())) {
					session.invalidate();
				}
			}*/
		}

		
		// rememberMeServices.loginSuccess(request, response, au);
		
		String path = request.getServletPath();
		if (path.startsWith("/admin/")) {
			super.setDefaultTargetUrl("/admin/index");
			super.setAlwaysUseDefaultTargetUrl(true);
		}
		super.onAuthenticationSuccess(request, response, au);
    }

}
